package ch.headshot.photomap.client;

import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.NodeList;

public class GPX {

	private final Document doc;

	public GPX(Document document) {
		this.doc = document;
	}

	LatLng[] getRoute(int idx) {
		Node rte = doc.getElementsByTagName("rte").item(idx);
		if (rte == null) {
			throw new NullPointerException("No rte found with idx " + idx);
		}
		NodeList rtepts = ((Element) rte).getElementsByTagName("rtept");
		int length = rtepts.getLength();
		LatLng[] result = new LatLng[length];
		for (int i = 0; i < length; i++) {
			Element item = (Element) rtepts.item(i);
			Double lat = Double.valueOf(item.getAttribute("lat"));
			Double lng = Double.valueOf(item.getAttribute("lon"));
			result[i] = LatLng.newInstance(lat, lng);
		}
		return result;
	}

	LatLng[] getTrack(int idx) {
		Node rte = doc.getElementsByTagName("trk").item(idx);
		if (rte == null) {
			throw new NullPointerException("No rte found with idx " + idx);
		}
		NodeList rtepts = ((Element) rte).getElementsByTagName("trkpt");
		int length = rtepts.getLength();
		LatLng[] result = new LatLng[length];
		for (int i = 0; i < length; i++) {
			Element item = (Element) rtepts.item(i);
			Double lat = Double.valueOf(item.getAttribute("lat"));
			Double lng = Double.valueOf(item.getAttribute("lon"));
			result[i] = LatLng.newInstance(lat, lng);
		}
		return result;
	}

}
